const WXAPI = require('apifm-wxapi')
const TOOLS = require('../../utils/tools.js')
const AUTH = require('../../utils/auth')
const CONFIG = require('../../config.js')
const APP = getApp()

Page({
  data: {
    qj: wx.getStorageSync("qj") || 'bz',
    zdydh: wx.getStorageSync("zdydh") || '',
    zdylogo: wx.getStorageSync("zdylogo") || '',
    dh_tap_index: 1,
    menuList: [],
    // 下拉菜单的选项数组（根据环境动态生成）
    array: [],
    selectedIndex: 0,
    caseIndex: undefined,
    showPop: false,
    caseIndexName0: '',
    caseIndexName1: '',
    caseIndexName2: '',
    caseIndexName3: '',
    caseIndexName4: '',
    caseIndexName5: '',
    articleList: [],
    page: 1,
    pageSize: 10,
    isLoading: false,
    noMoreData: false,
    k: '',
    // 新增：节流控制
    scrollThrottling: false
  },

  onLoad: function (e) {
    this.setData({
      selectedIndex: e.selectedIndex || 0,
      caseIndexName0: e.caseIndexName0?decodeURIComponent(e.caseIndexName0) : '',
      caseIndexName1: e.caseIndexName1?decodeURIComponent(e.caseIndexName1) : '',
      caseIndexName2: e.caseIndexName2?decodeURIComponent(e.caseIndexName2) : '',
      caseIndexName3: e.caseIndexName3?decodeURIComponent(e.caseIndexName3) : '',
      caseIndexName4: e.caseIndexName4?decodeURIComponent(e.caseIndexName4) : '',
      caseIndexName5: e.caseIndexName5?decodeURIComponent(e.caseIndexName5) : '',
    });
    if (e.caseIndexName0 || e.caseIndexName1 || e.caseIndexName2 || e.caseIndexName3 || e.caseIndexName4 || e.caseIndexName5) {
      const caseIndexNames = [
        e.caseIndexName0, e.caseIndexName1, e.caseIndexName2,
        e.caseIndexName3, e.caseIndexName4, e.caseIndexName5
      ];

      // 过滤空值（保留有效字符串）
      const validNames = caseIndexNames.filter(name => {
        // 排除 undefined、null、空字符串（包括纯空格）
        return name !== undefined && name !== null && name.trim() !== '';
      });

      // 用逗号拼接有效数据（如果没有有效数据则设为空）
      const newK = validNames.length > 0 ? validNames.join(',') : '';

      this.setData({
        k: decodeURIComponent(newK)
      });
      console.log("dddd",this.data.k);
      
    }
    // 初始化下拉菜单选项（根据环境）
    this.initArrayOptions();
    // 加载页面数据和文章列表
    this.cmsPage();
    this.loadArticles();
  },

  onShow: function () {
    const currentQj = wx.getStorageSync("qj") || 'bz';
    // 环境变化时重新初始化选项并刷新数据
    if (currentQj !== this.data.qj) {
      this.setData({ qj: currentQj });
      this.initArrayOptions();
      this.resetArticleList();
      this.loadArticles();
    }
  },

  // 初始化下拉菜单选项
  initArrayOptions() {
    const isZh = this.data.qj == 'hz' || this.data.qj == 'bz';
    this.setData({
      array: isZh ? ['图库', '整案'] : ['Gallery', 'Case']
    });
  },

  // 重置文章列表（用于切换分类或环境时）
  resetArticleList() {
    this.setData({
      articleList: [],
      page: 1,
      noMoreData: false
    });
  },

  article_detail(e) {
    const id = e.currentTarget.dataset.id;
    if (!id) {
      wx.showToast({ title: '参数错误', icon: 'none' });
      return;
    }
    // 根据选中的分类跳转到不同详情页
    const url = this.data.selectedIndex == 0
      ? `/packageYt/case/detail_kt?id=${id}`
      : `/packageYt/case/detail_za?id=${id}`;
    wx.navigateTo({ url });
  },

  // 加载文章列表（核心方法）
  async loadArticles() {
    // 防止重复请求或无更多数据时继续请求
    if (this.data.isLoading || this.data.noMoreData) return;

    // 显示加载中状态
    this.setData({ isLoading: true });

    try {
      // 确定分类ID（图库：200812，整案：200813）
      const categoryId = this.data.selectedIndex == 0 ? '200812' : '200813';
      console.log("k", this.data.k);

      const res = await WXAPI.cmsArticles({
        categoryId,
        k: this.data.k ? this.data.k : '', // 处理空搜索词
        page: this.data.page,
        pageSize: this.data.pageSize
      });

      // 处理无数据情况
      if (res.code == 700) {
        this.setData({ noMoreData: true });
        return;
      }

      // 处理正常返回数据
      if (res.code == 0) {
        const newArticles = res.data.result || [];
        const oldArticles = this.data.articleList;
        const total = res.data.totalRow || 0;

        // 拼接新数据
        this.setData({
          articleList: oldArticles.concat(newArticles),
          page: this.data.page + 1
        });

        // 判断是否已加载全部
        if (this.data.articleList.length >= total) {
          this.setData({ noMoreData: true });
        }
      } else {
        wx.showToast({ title: res.msg || '加载失败', icon: 'none' });
      }
    } catch (err) {
      console.error('加载失败：', err);
      wx.showToast({ title: '网络异常', icon: 'none' });
    } finally {
      // 无论成功失败，都关闭加载中状态
      this.setData({ isLoading: false });
    }
  },

  // 官方推荐的页面触底事件（替代onScrollToBottom）
  onReachBottom() {
    // 节流处理：300ms内只允许触发一次
    if (!this.data.scrollThrottling) {
      this.setData({ scrollThrottling: true });
      this.loadArticles();
      setTimeout(() => {
        this.setData({ scrollThrottling: false });
      }, 300);
    }
  },

  // 筛选条件选择
  case_nav_footer(e) {
    const name = e.currentTarget.dataset.name || '';
    const nameEn = e.currentTarget.dataset.nameEn || '';
    const currentCaseIndex = this.data.caseIndex;

    if (currentCaseIndex == undefined || currentCaseIndex == '-1' || !name) return;

    // 确定当前要使用的关键词（中文/英文）
    const currentName = (this.data.qj == 'hz' || this.data.qj == 'bz') ? name : nameEn;

    // 将现有关键词拆分成数组（处理空值和逗号）
    let kArray = this.data.k ? this.data.k.split(',').filter(item => item.trim() !== '') : [];

    // 清除当前分类下的历史关键词
    const caseIndexNames = [
      'caseIndexName0', 'caseIndexName1', 'caseIndexName2',
      'caseIndexName3', 'caseIndexName4', 'caseIndexName5'
    ];
    const prevName = this.data[caseIndexNames[currentCaseIndex]] || '';
    if (prevName) {
      kArray = kArray.filter(item => item !== prevName);
    }

    // 添加新关键词（去重）
    if (!kArray.includes(currentName)) {
      kArray.push(currentName);
    }

    // 数组转字符串（用逗号分隔）
    const newK = kArray.join(',');

    // 更新数据
    this.setData({
      k: newK,
      [caseIndexNames[currentCaseIndex]]: currentName,
      showPop: false
    });

    console.log("筛选关键词：", this.data.k);

    // 重置并重新加载数据
    this.resetArticleList();
    this.loadArticles();
  },

  // 打开/关闭筛选弹窗
  case_nav(e) {
    const temp = e.currentTarget.dataset.index;
    this.setData({
      caseIndex: temp,
      showPop: !this.data.showPop // 切换弹窗状态
    });
  },

  // 加载页面配置
  async cmsPage() {
    try {
      const res = await WXAPI.cmsPage("yt0000");
      if (res.code == 0) {
        let sj = JSON.parse(res.data.info.content);
        this.setData({
          menuList: sj.menuList || []
        });
      } else {
        console.error('cmsPage加载失败：', res.msg);
      }
    } catch (err) {
      console.error('cmsPage接口异常：', err);
    }
  },

  // 下拉选项改变
  bindPickerChange(e) {
    const selectedIndex = e.detail.value;
    if (selectedIndex == this.data.selectedIndex) return; // 避免重复操作

    this.setData({ selectedIndex });
    // 重置并重新加载数据
    this.resetArticleList();
    this.loadArticles();

    // 分类切换日志
    console.log(selectedIndex == 0 ? '选择了图库' : '选择了整案');
  },

  // 自定义导航跳转
  zdy_top_nav() {
    wx.navigateTo({ url: '/pages/xl/index' });
  },

  // 底部导航切换
  dh_tap(e) {
    const temp = e.currentTarget.dataset.id;
    if (temp == this.data.dh_tap_index) return; // 避免重复跳转

    this.setData({ dh_tap_index: temp });

    // 导航路径映射
    const urlMap = [
      '/packageYt/index/index',
      '/packageYt/case/index',
      '/packageYt/ting/index',
      '/packageYt/goods/index',
      '/packageYt/my/index'
    ];

    if (temp >= 0 && temp < urlMap.length) {
      wx.reLaunch({ url: urlMap[temp] });
    }
  },

  // 商品列表加载（备用方法）
  async getGoodsList(categoryId, append) {
    if (categoryId == 0) categoryId = "";

    wx.showLoading({ title: '' });
    try {
      const res = await WXAPI.goodsv2({
        categoryId,
        page: this.data.curPage || 1,
        pageSize: this.data.pageSize
      });

      if (res.code == 404 || res.code == 700) {
        let newData = { loadingMoreHidden: false };
        if (!append) newData.goods = [];
        this.setData(newData);
        return;
      }

      let goods = append ? this.data.goods : [];
      const hiddenGoodsIndex = wx.getStorageSync('hidden_goods_index') || [];

      res.data.result.forEach(item => {
        if (!hiddenGoodsIndex.includes(item.id)) {
          goods.push(item);
        }
      });

      this.setData({
        loadingMoreHidden: true,
        goods
      });
    } catch (err) {
      console.error('商品列表加载失败：', err);
    } finally {
      wx.hideLoading();
    }
  },

  // 分享配置
  onShareAppMessage() {
    let params = 'selectedIndex=' + this.data.selectedIndex;
    if (this.data.caseIndexName0 != '') {
      params += '&caseIndexName0=' + this.data.caseIndexName0;
    }
    if (this.data.caseIndexName1 != '') {
      params += '&caseIndexName1=' + this.data.caseIndexName1;
    }
    if (this.data.caseIndexName2 != '') {
      params += '&caseIndexName2=' + this.data.caseIndexName2;
    }
    if (this.data.caseIndexName3 != '') {
      params += '&caseIndexName3=' + this.data.caseIndexName3;
    }
    if (this.data.caseIndexName4 != '') {
      params += '&caseIndexName4=' + this.data.caseIndexName4;
    }
    if (this.data.caseIndexName5 != '') {
      params += '&caseIndexName5=' + this.data.caseIndexName5;
    }


    const sharePath = `/packageYt/case/index?${params}`;

    return {
      title: `"${wx.getStorageSync('mallName')}" ${wx.getStorageSync('share_profile')}`,
      path: sharePath,
    };
  },

  onShareTimeline() {
    let params = 'selectedIndex=' + this.data.selectedIndex;
    if (this.data.caseIndexName0 != '') {
      params += '&caseIndexName0=' + this.data.caseIndexName0;
    }
    if (this.data.caseIndexName1 != '') {
      params += '&caseIndexName1=' + this.data.caseIndexName1;
    }
    if (this.data.caseIndexName2 != '') {
      params += '&caseIndexName2=' + this.data.caseIndexName2;
    }
    if (this.data.caseIndexName3 != '') {
      params += '&caseIndexName3=' + this.data.caseIndexName3;
    }
    if (this.data.caseIndexName4 != '') {
      params += '&caseIndexName4=' + this.data.caseIndexName4;
    }
    if (this.data.caseIndexName5 != '') {
      params += '&caseIndexName5=' + this.data.caseIndexName5;
    }
    return {
      title: `"${wx.getStorageSync('mallName')}" ${wx.getStorageSync('share_profile')}`,
      query: params
    };
  },

  // 下拉刷新功能
  onPullDownRefresh() {
    this.resetArticleList();
    this.loadArticles().then(() => {
      wx.stopPullDownRefresh(); // 结束刷新动画
    });
  }
})